<?php

class WxPayController extends WechatAppController{
	
	public function beforeFilter(){
		parent::beforeFilter();
	    $this->Auth->allow('payback');
	}

	public function pay(){
	    $token = isset($this->request->query['token'])?true:false;
	    $id = $order_id = $this->request->query['id'];
    	$this->loadModel('UserOrder');
    	$this->UserOrder->recursive = -1;
    	$order = $this->UserOrder->findById($order_id);
        $serial = $order['UserOrder']['ordernum'];
    	$param = array(
    		'body'=>'和平票务-购票费用['.$serial.']',
    	    'attach'=>'',
    	    'out_trade_no'=>$order['UserOrder']['ordernum'],
			'fee'=>$order['UserOrder']['price_total'],
    	    'tag'=>'',
    	    'notify'=>Router::url('/',true).'wechat/WxPay/payback'
		);
    	$this->set('order',$order);
    	$return = Router::url('/',true).'UserOrders_view_'.$id;
    	$render = 'order';
	    
	    if($token){
	        $this->layout = 'ajax';
	        $user_agent = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
        	$type = 'JSAPI';
	        if (strpos($user_agent, 'MicroMessenger') === false) {
	        	$type = 'WAP';
        	}
	        $jsApiParameters = $this->WxPay->getJsApi($this->Auth->user('ext_wx_openid'),$param,$type);
	        if(isset($jsApiParameters['return_code']) && $jsApiParameters['return_code'] == 'FAIL'){
	            $state = false;
	            $msg = $jsApiParameters['return_msg'];
	        }else{
	            $state = true;
	        }
	        $this->set(compact('jsApiParameters','state','msg','return'));
	        if($type == 'JSAPI'){
		        $this->render('pay');
	        }else{
        		$this->render('pay_out');
	        }
	        return;
	    }
	    
	    $this->loadModel('Wechat.Wechat');
	    $jsApiConfig = $this->Wechat->jsApiConfig();
	    $this->set(compact('jsApiConfig','type','id','serial'));
	    $this->render($render);
	}
	
    public function payback() {
        $this->AutoRender = false;
        $notify = new WxPayNotifyCallBack();
        $notify->Handle(false);
	    $this->render(false);
	}
	
}

App::import('Vendor','Wechat.WxPayApi',array('file'=>'wxpay'.DS.'WxPay.Api.php'));
App::import('Vendor','Wechat.WxPayNotify',array('file'=>'wxpay'.DS.'WxPay.Notify.php'));
class WxPayNotifyCallBack extends WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        App::import('Model','UserOrder');
        $OrderObj = new UserOrder();
        $serial = $data['out_trade_no'];
        $OrderObj->recursive = -1;
        $order = $OrderObj->findByOrdernum($serial);
        //Cache::write('log', $order+$data);
    	if($order['UserOrder']['user_order_state_id'] == 1){
	    	$order_id = $order['UserOrder']['id']; 
	    	$res = $OrderObj->updateOrderState($order_id,2,6,'【微信移动支付】'.$data['transaction_id']);
    	}else{
    		$res = false;
    	}
        if($res){
            return true;
        }else{
            return false;
        }
    }
}
